<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/mineBg.png" mode="widthFix"></image>
		</view>
		<cusHeaderVue titleContent="我的任务" :showBack="true" :useDefaultBack="!fromFeedbackSuccess" @back="handleBack"></cusHeaderVue>
		<view class="tabBox" :style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`}">
			<view class="tabLi" :class="tabIndex==0?'tabLiA':''" @click="chooseTab(0)">
				未完成<text>{{taskCounts.uncompleted}}</text>
			</view>
			<view style="width: 100rpx;">
				
			</view>
			<view class="tabLi" :class="tabIndex==1?'tabLiA':''" @click="chooseTab(1)">
				已完成<text>{{taskCounts.completed}}</text>
			</view>
		</view>
		<view class="inptBox">
			<image src="/static/home/searchIcon.png" mode=""></image>
			<input type="text" v-model="searchKey" placeholder="请输入关键字搜索" placeholder-style="color: #BBC0CB;" @input="handleSearch"/>
		</view>
		<scroll-view scroll-y="true" :style="{height: `calc(100vh - ${scrollerHeight} - 90rpx - 195rpx)`}">
			<view class="scrollBox">
				<view v-if="loading" class="loading">
					加载中...
				</view>
				<view v-else-if="taskList.length === 0" class="empty">
					暂无任务数据
				</view>
				<view v-else class="boxLi" v-for="(item, index) in taskList" :key="item.id || index" @click="toTaskDetail(item)">
					<view class="boxTop">
						<view class="boxName">
							任务类型：{{item.taskType || '未知类型'}}
							<view class="boxStatus" :class="{ 'statusCompleted': item.status === 1 }">
								{{ item.status === 0 ? '未完成' : '已完成' }}
							</view>
						</view>
						<u-icon name="arrow-right" color="#b7b6c3" size="15"></u-icon>
					</view>
					<view class="boxTip">
						<text>任务描述：</text>{{item.description || '暂无描述'}}
					</view>
					<view class="boxTip">
						<text>计划完成时间：</text>{{item.dueDate || '未设置'}}
					</view>
					<view class="boxTip" v-if="item.status === 1">
						<text>实际完成时间：</text>{{item.successTime || '未设置'}}
					</view>
					<view class="boxTip">
						<text>下发人：</text>{{item.dxTaskDO.createUserName || '系统'}}
					</view>
					<view class="boxStatusIcon">
						<image :src="item.status === 0 ? '/static/mine/wcxs.png' : '/static/mine/ywclb.png'" mode=""></image>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import cusHeaderVue from '@/components/cus-header.vue';
	import { GETTaskAgencyList } from '@/api/interface.js';
	const scrollerHeight = ref('');
	const tabIndex = ref(0);
	const taskList = ref([]);
	const loading = ref(false);
	const searchKey = ref('');
	const taskCounts = ref({
		uncompleted: 0,
		completed: 0
	});
	const searchTimer = ref(null);
	// 标记是否从反馈成功页进入，用于单次返回到“我的”页
	const fromFeedbackSuccess = ref(false);

	const handleBack = () => {
		if (fromFeedbackSuccess.value) {
			// 从反馈成功页进入，单次返回直达“我的”页（tab）
			uni.switchTab({ url: '/pages/mine/mine' });
		} else {
			// 其他来源，维持默认返回
			uni.navigateBack({ delta: 1 });
		}
	};
    const chooseTab = (index) => {
		tabIndex.value = index;
		// 切换tab时重新调用接口
		getTaskList();
	};

	// 任务类型映射
	const taskTypeMap = {
		1: '竞品调研',
		2: '仓库整理',
		3: '项目支援'
	};

	// 获取任务列表
	const getTaskList = async () => {
		loading.value = true;
		try {
			// 准备查询参数
			const params = {
				status: tabIndex.value === 0 ? '0' : '1', // 0表示未完成，1表示已完成
				title: searchKey.value || ''
			};
			
			// 调用接口
			const res = await GETTaskAgencyList(params);
			// 适配新的API返回格式 {"code":0,"msg":"","data":{"wwc":0,"ywc":1,"list":[...]}}
			if (res.code === 0 && res.data) {
				// 更新任务数量
				taskCounts.value.uncompleted = res.data.wwc || 0;
				taskCounts.value.completed = res.data.ywc || 0;
				
				// 从data.list获取任务列表并处理数据映射
				taskList.value = (res.data.list || []).map(item => {
					// 获取任务类型对应的中文标签
					const taskTypeValue = item.dxTaskDO?.taskType;
					const taskTypeLabel = taskTypeMap[taskTypeValue] || '未知类型';
					
					return {
						id: item.id,
						status: item.status,
						taskType: taskTypeLabel,
						description: item.dxTaskDO?.description || '暂无描述',
						dueDate: item.dxTaskDO?.completionTime ? formatDate(item.dxTaskDO.completionTime) : '未设置',
						successTime: item.dxTaskDO?.updateTime ? formatDate(item.dxTaskDO.updateTime) : '未设置',
						assignerName: item?.nickName || '系统',
						// 保留原始数据以便其他需要
						originalData: item,
						// 保留dxTaskDO完整数据供详情页使用
						dxTaskDO: item.dxTaskDO
					};
				});
			} else {
				uni.showToast({
					title: res.msg || '获取任务失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取任务列表失败:', error);
			uni.showToast({
				title: '获取任务失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};


const formatDate = (timestamp) => {
		if (!timestamp) return '';
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	}

	// 日期格式化函数
	// const formatDate = (dateString) => {
	// 	if (!dateString) return '未设置';
	// 	const date = new Date(dateString);
	// 	if (isNaN(date.getTime())) return '未设置';
	// 	const year = date.getFullYear();
	// 	const month = String(date.getMonth() + 1).padStart(2, '0');
	// 	const day = String(date.getDate()).padStart(2, '0');
	// 	const day = String(date.getDate()).padStart(2, '0');
	// 	return `${year}-${month}-${day}`;
	// };

	// 搜索功能
	const handleSearch = () => {
		// 添加防抖处理
		clearTimeout(searchTimer.value);
		searchTimer.value = setTimeout(() => {
			getTaskList();
		}, 500);
	};

	// 跳转到任务详情
	const toTaskDetail = (item) => {
		// 本地存储任务数据
		uni.setStorageSync('currentTaskData', item);
		const url = item.status === 1 ? '/pages/mine/taskXqYwc' : '/pages/mine/taskXqWwc';
		// 传递完整的dxTaskDO数据到详情页
		uni.navigateTo({
			url: `${url}`
		});
	};

	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px';
			}
		});
	};

	onLoad((options) => {
		getBarHeight();
		// 如果由反馈成功页跳转而来，设置完成Tab并标记来源
		if (options && (options.from === 'feedbackSuccess')) {
			fromFeedbackSuccess.value = true;
			// 如果带了tab=1，则切到已完成
			if (String(options.tab) === '1') {
				tabIndex.value = 1;
			}
		}
	});

	onShow(() => {
		// 页面显示时重新获取任务列表
		getTaskList();
	});
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}
	
	.bgColor {
		width: 100%;
		position: absolute;
		z-index: -1;
		top: 0;
	
		image {
			width: 100%;
			height: 100%;
		}
	}
	
	.tabBox{
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50rpx;
		.tabLi{
			font-size: 29.49rpx;
			font-weight: 400;
			color: #3F3F3F;
			position: relative;
			text{
				margin-left: 9rpx;
			}
		}
		.tabLiA{
			font-weight: 500;
			font-size: 29.49rpx;
			color: #000000;
		}
		.tabLiA::after {
			content: "";
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			bottom: -10rpx;
			flex: 1;
			width: 61.54rpx;
			height: 6.41rpx;
			border-radius: 3.21rpx 3.21rpx 3.21rpx 3.21rpx;
			background: linear-gradient(-90deg, #feaf38,#f98434);
		}
	}
	.inptBox{
		width: 705rpx;
		height: 70rpx;
		border-radius: 35.26rpx 35.26rpx 35.26rpx 35.26rpx;
		background: #ffffff;
		box-shadow: 0.64rpx 1.28rpx 13.46rpx 0 #e19a2e29;
		margin: 45rpx auto 0;
		display: flex;
		align-items: center;
		padding: 0 27rpx;
		box-sizing: border-box;
		margin-bottom: 19rpx;
		image{
			width: 30.13rpx;
			height: 30.13rpx;
		}
		input{
			flex: 1;
			font-weight: 400;
			font-size: 28.21rpx;
			
			margin-left: 12rpx;
		}
	}
	.scrollBox{
			.loading,
			.empty {
				text-align: center;
				padding: 60rpx 0;
				color: #999;
				font-size: 28rpx;
			}
		
		.boxLi{
			width: 705rpx;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			margin: 0 auto 22rpx;
			padding: 37rpx 27rpx;
			box-sizing: border-box;
			position: relative;
			.boxTop{
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 14rpx;
				.boxName{
					font-weight: 500;
					font-size: 33.33rpx;
					color: #1C2027;
					display: flex;
					align-items: center;
					.boxStatus{
						width: 94.87rpx;
						height: 38.46rpx;
						border-radius: 7.69rpx 7.69rpx 7.69rpx 7.69rpx;
						background: #fd503e;
						font-size: 24.36rpx;
						font-weight: 400;
						color: #FFFFFF;
						margin-left: 13rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
			}
			.boxTip{
				color: #2d2d2d;
				 font-weight: 400;
				 font-size: 25.64rpx;
				 line-height: 48.72rpx;
				 text{
					  color: #7f8494;
				 }
			}
			.boxStatusIcon{
				width: 123.72rpx;
				height: 123.72rpx;
				position: absolute;
				right: 29rpx;
				bottom: 37rpx;
				image{
					width: 100%;
					height: 100%;
				}
			}
		}
	}
</style>